package com.hugo.vod.service.impl;


import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.hugo.commonutiles.R;
import com.hugo.serviceconfig.exceptionhandler.HugoException;
import com.hugo.vod.Utils.ConstantVodUtils;
import com.hugo.vod.Utils.InitVideo;
import com.hugo.vod.service.VodService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

import static com.hugo.vod.Utils.ConstantVodUtils.KEYID;
import static com.hugo.vod.Utils.ConstantVodUtils.KEYSECRET;


@Service
public class VodServiceImpl implements VodService {

    @Override
    public String uploadVideoAliyun(MultipartFile file) {
        try{
        //获取上传文件名字
        String originalFilename=file.getOriginalFilename();
        //上传文件原始名称
        String title = originalFilename.substring(0, originalFilename.lastIndexOf("."));
        //上传文件输入流
        InputStream inputStream=file.getInputStream();
        UploadStreamRequest request = new UploadStreamRequest(KEYID, KEYSECRET, title, originalFilename, inputStream);
        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadStreamResponse response = uploader.uploadStream(request);
        String videoId =null;
        if (response.isSuccess()) {
            videoId = response.getVideoId();
        } else {
            videoId = response.getVideoId();
        }
        return videoId;
        }
        catch (Exception e){
            return null;
        }
    }

    @Override
    public void removeAliyunVideo(List viedoIdList) {
        try
        {
            //初始化对象
            DefaultAcsClient client = InitVideo.initVodClient(ConstantVodUtils.KEYID, ConstantVodUtils.KEYSECRET);
            //创建删除视屏的request对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            //传入数组  用逗号将其分开
            String videoIds = StringUtils.join(viedoIdList.toArray(), ",");
            //想request设置id
            request.setVideoIds(videoIds);
            //执行删除方法
            client.getAcsResponse(request);

        } catch (Exception e){
            throw  new HugoException(20001,"视屏删除失败");
        }
    }
}
